import 'package:aitao_flutter/common_ui/back_nav.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../common_ui/loading_view.dart';
import '../../model/cost_level_model.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../style/box_style.dart';
import '../../style/color_style.dart';
import '../../style/edgeInsets_style.dart';

class VideoCostPage extends StatefulWidget {
  const VideoCostPage({super.key});

  @override
  State<VideoCostPage> createState() => _VideoCostPageState();
}

class _VideoCostPageState extends State<VideoCostPage> {
  bool loading = true;
  String rule = '';
  List<CostLevelModel> levelList = [];
  int currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BackNavigation(
        title: '通话价格',
        rightTitle: '保存',
        rightBtnCallBack: () {
          setCostLevel();
        },
      ),
      body: loading == false
          ? CustomScrollView(
              slivers: [_levelList(), _rulesWidget()],
            )
          : const LoadingView(),
    );
  }

  Widget _levelList() {
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      CostLevelModel levelModel = levelList[index];
      return GestureDetector(
        child: Container(
          padding: const EdgeInsets.all(15),
          color: ColorStyle.whiteColor,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                levelModel.title ?? '',
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: levelModel.isDisable == 0
                        ? ColorStyle.color333333
                        : ColorStyle.aaaaaaColor),
              ),
              Box.hBox10,
              Text(
                levelModel.remark ?? '',
                style:
                    TextStyle(fontSize: 10.sp, color: ColorStyle.aaaaaaColor),
              ),
              const Spacer(),
              Icon(
                Icons.check_rounded,
                color: levelModel.isShow
                    ? ColorStyle.themeColor
                    : ColorStyle.whiteColor,
              )
            ],
          ),
        ),
        onTap: () {
          if (currentIndex == index) {
            return;
          }
          CostLevelModel levelModel = levelList[index];
          if (levelModel.isDisable == 1) {
            EasyLoading.showToast('该等级不可选');
            return;
          }
          for (CostLevelModel element in levelList) {
            element.isShow = false;
          }
          setState(() {
            levelList[index].isShow = true;
            currentIndex = index;
          });
        },
      );
    }, childCount: levelList.length));
  }

  Widget _rulesWidget() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsetsStyle.edgeInsets(22, 18),
        child: Text(rule,
            style:
                const TextStyle(fontSize: 14, color: ColorStyle.color999999)),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    getLevelList();
  }

  void getLevelList() async {
    var result = await RequestManager().post(API.levelPriceList);
    if (result != null && result['code'] == 0) {
      loading = false;
      rule = result['data']['rule'].toString();
      List tempList = result['data']['list'];
      levelList = tempList.map((e) {
        return CostLevelModel.fromJson(e);
      }).toList();
      for (var i = 0; i < levelList.length; i++) {
        CostLevelModel model = levelList[i];
        for (CostLevelItem item in model.items!) {
          if (item.isCurrentLevel == 1) {
            currentIndex = i;
            model.isShow = true;
          }
        }
      }
      setState(() {});
    }
  }

  void setCostLevel() async {
    int levelId = levelList[currentIndex].items?.last.levelId ?? 0;
    if (levelId == 0) return;
    Map params = {'level_id': levelId, 'skill_id': 0};
    var result = await RequestManager().post(API.setLevelPrice, params: params);
    if (result != null && result['code'] == 0) {
      EasyLoading.showToast(result['message']);
      Future.delayed(const Duration(milliseconds: 500), () {
        Get.back();
      });
    }
  }
}
